$(document).ready(function () {

    let uploadType = '1';
    // 初始化时间控件
    initTimeDataControl('startTime', publicNewDay1);
    initTimeDataControl('endTime', publicNewDay1);
    tableData1();
    $('#conditionScheduleStartTime').datetimepicker({
        language: 'zh-CN'
        , autoclose: true
        , todayHighlight: true
        , format: 'yyyy-mm-dd'
        , startView: 'month'//视图到月
        , minView: 'month'//最小视图到月
    }).on('changeDate', function (e) {//日期改变事件
    });
    // 表格内置滚动
    tableBuiltInScroll('dataTableBox', 380);
});

// 自定义预测数据上传
let table1 = null;
var fileName = '';//文件名称
function tableData1() {
    if (table1 != null) {
        table1.destroy();
        table1 = null;
    }
    $("#data-table").html("");//清空表格

    let aoColumns = [
        // {
        //     "mData": "userName",
        //     "sTitle": "模块"
        // },
        // {
        //     "mData": "userName",
        //     "sTitle": "供应商"
        // },
        {
            "mData": "originalName",
            "sTitle": "需求文件名称"
        },
        // {
        //     "mData": "originalName",
        //     "sTitle": "上传文件名称"
        // },
        {
            "mData": "handleStatusName",
            "sTitle": "上传状态",
            "render": function (data, type, row) {
                let msg = row.runLog;
                if (msg != null && msg != 'null' && msg != '') {
                    msg = msg.replace(/'/g, '');
                    return '<a onclick="errorHint(\'' + encodeURI(msg) + '\')">' + row.handleStatusName + '</a>';
                }
                return msg;
            }
        },
        {
            "mData": "userName",
            "sTitle": "上传人"
        },
        {
            "mData": "createTime",
            "sTitle": "上传时间"
        },
        {
            "mData": "updateTime",
            "sTitle": "数据更新时间"
        }
    ];

    if ($("#hasDownloadPermission").val() === '1') {
        aoColumns.push({
            "sTitle": "操作",
            "render": function (data, type, row) {
                let newName = row.newName;
                let btnGroup = '';
                if (newName != null && newName != 'null' && newName != '') {
                    btnGroup = '<a class="btn blue" style="font-size: 12px;" onclick="showUploadCustomBox(\'' + encodeURI(row.originalName) + '\')">京东上传文件</a>  '+
                        '<a class="btn blue" style="font-size: 12px;" onclick="showUploadCustomBox(\'' + encodeURI(row.originalName) + '\')">AI上传文件</a>  ' +
                        '<a class="btn blue" style="font-size: 12px;" onclick="downloadExcel(' + row.id + ')">下载</a>'
                }
                return btnGroup;
            }
        });
    }

    let params = {
        start_date: $("#startTime").val(),
        end_date: $("#endTime").val(),
        mokuai: $("#scheduleGroup").val(),
        gongyingshang: $("#scheduleShift").val(),
        handleStatusName: $("#schedulePosition").val(),
        userName: $("#userName").val(),
    };
    table1 = $('#data-table').DataTable({
        ajax: {
            url: "../uploadCustomPredict/getUploadLogList",
            data: params,
            dataSrc: function (data) { // 这是从服务器接受的数据（名称、格式）
                if (data.success) {
                    if (!data.data.length) {
                        return 0;
                    }
                    return data.data; // 返回表格中的数据
                } else {
                    MyBaseJs.alert1(data.msg)
                }
            }
        },
        "aoColumns": aoColumns,
        "language": {
            "sProcessing": "正在获取数据，请稍后...",
            "sLengthMenu": "每页 _MENU_ 条记录",
            "sZeroRecords": "没有您要的内容",
            "sInfo": "从 _START_ 到  _END_ 条记录 总记录数为 _TOTAL_ 条，第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
            "sInfoEmpty": "无记录",
            "sInfoFiltered": "",
            "sInfoPostFix": "",
            "sSearch": "搜索",
            "sUrl": "",
            "oPaginate": {
                "sFirst": "第一页",
                "sPrevious": "上一页",
                "sNext": "下一页",
                "sLast": "最后一页"
            }
        },
        "searching": true,
        "autoWidth": false,
        "bProcessing": true,
        "scrollX": true, // X方向滚动
        "scrollY": "380px",
        "ordering": false, // 禁止排序
        // "serverSide": true,	//打开后台分页
        buttons: [

        ],
        "dom": "<'row' <'col-md-11 col-sm-11'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>"
    });
}

// 方案运行失败提示
function errorHint(errorMsg) {
    MyBaseJs.alert1(decodeURI(errorMsg));
}

// 删除
function deleteData(id) {
    majorId = id;
    $("#myModal_autocomplete2").modal();
}

// 确认删除
function removeData() {
    $.ajax({
        type: 'get',
        url: '../uploadCustomPredict/deleteUploadLog',
        data: {
            id: majorId
        },
        dataType: "json", // 返回数据形式为json
        success: function (data) {
            if (data.success) {
                MyBaseJs.alert('操作成功！');
                tableData1();
                $("#myModal_autocomplete2").modal('hide');
            } else {
                MyBaseJs.alert1(data.msg);
            }
        }
    });
}


// 自定义预测数据
function showUploadCustomBox(name) {
    uploadType = '1';
    fileName = name + '';
    console.log('fileName----', fileName)
    $("#importExcelView").modal();
}

function showUploadCustomBoxAI(name) {
    uploadType = '2';
    fileName = name + '';
    $("#importExcelView").modal();
}

// 导入自定义预测数据excl
function uploadCustomExcel() {
    if ("" == $("#conditionScheduleStartTime").val()) {
        MyBaseJs.alert1("请选择日期");
    } else if ("" == $("#excelFile").val()) {
        MyBaseJs.alert1("请选择excel文件");
    } else if (!$("#excelFile").val().endsWith(".xlsx") && !$("#excelFile").val().endsWith(".xls")) {
        MyBaseJs.alert1("请选择有效的excel文件");
    } else {
        /!* 上传文件 *!/
        MyBaseJs.openMask("正在导入。。。");
        $("#importExcelView").modal("hide");
        let url=""
        if(uploadType==1){
            url=base + "/file/uploadSheetExcelFile"
        }else{
            url=base + "/file/uploadSheetExcelFileAI"
        }
        $.ajaxFileUpload({
            url: url,
            secureuri: true,
            dataType: "json",
            fileElementId: "excelFile",
            data: {
                uploadDate: $("#conditionScheduleStartTime").val()
            },
            success: function (data) {
                MyBaseJs.closeMask();
                if (data.success != null && data.success != "") {
                    MyBaseJs.alert(data.msg);
                } else if (data.error != null && data.error != "") {
                    MyBaseJs.alert1(data.error);
                } else if (data.msg != null && data.msg != "") {
                    MyBaseJs.alert1(data.msg);
                } else {
                    MyBaseJs.alert1("服务器异常！");
                }
            }
        });
    }
}

//下载excel
function downloadExcel(id) {
    window.location.href = base + "/uploadCustomPredict/downloadExcel?id=" + id;
}

// 下载模板
function downloadTemplate() {
    window.location.href = base + '/file/downloadSheetExcelTemplate?originalName=' + decodeURI(fileName);
}

// 查询
function scheduleInquire() {
    tableData1();
    // $('.scheduleManagementText').hasClass('toolActiveText') ? getScheduleData() : scheduleStatistics();
}